package com.paipai.loginInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.paipai.jwtproperty.JwtProperties;
import com.paipai.utils.CookieUtils;
import com.paipai.utils.JwtUtils;
import com.paipai.utils.UserInfo;
/**
 * 订单拦截器
 * @author zjw
 *
 */
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

	private static final ThreadLocal<UserInfo> tlocal = new ThreadLocal<UserInfo>();

	@Autowired
	private JwtProperties jwp;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 从cookie获取token
		String token = CookieUtils.getCookieValue(request, "loginToken");
		System.out.println("被拦截");

		// 直接拦截 未登录
		if (token == null) {
			// 返回403
			response.getWriter().write("403");
			return false;

		}

		try {
			// 解析token
			UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwp.getPublicKey());
			// 解析成功放入线程变量
			tlocal.set(userInfo);
			//放行
			System.out.println("放行");
			return true;
		} catch (Exception e) {
			//token解析错误
			// 返回403 未登录
			response.getWriter().write("403");
			return false;

		}
	}
	
	
	
	//线程结束后删除线程变量
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		tlocal.remove();
	}




	//获取线程变量
	public static UserInfo getTlocal() {
		return tlocal.get();
	}
	
	
	

}
